<template>
<div>
        <!-- 导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>权限列表</el-breadcrumb-item>        
    </el-breadcrumb>
    
    <!-- 卡片区域 -->
    <el-card>
<!-- 添加角色图标区域 -->
         <el-row>
                <el-col>
                    <el-button type='primary' >添加角色</el-button>
                </el-col>
            </el-row>   

            <!-- 角色列表区域 -->

            <el-table  :data='rolesList' border stripe>
                <el-table-column  type='expand' > 
                    <template slot-scope='scope'> 
                        <el-row  :class="['bdbottom',i1===0?'bdtop':' ','vcenter']" v-for='(item1,i1) in scope.row.children' :key='item1.id'>
                            <!-- 渲染一级权限 -->
                            <el-col :span='5'>
                                {{i1}}
                                <el-tag closable @close='removeRightById(scope.row,item1.id)'>{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>

                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span='19'>
                                <!-- 通过for嵌套 -->
                                <el-row  :class="[i2===0?'':'bdtop','vcenter']"   v-for='(item2,i2) in item1.children' :key='item2.id'>
                                    <el-col :span='6'>
                                        {{i2}}
                                        <el-tag closable @close='removeRightById(scope.row,item2.id)' type='success'>{{item2.authName}}
                                            
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span='18'>
                                        <el-tag closable @close='removeRightById(scope.row,item3.id)' type='warning' v-for='(item3,i3) in item2.children' :key="item3.id">
                                            {{i3}}
                                            
                                            {{item3.authName}}
                                            
                                        </el-tag>
                                        
                                    </el-col>
                                </el-row>


                            </el-col>
                        </el-row>
                        <pre>
                            {{scope.row}}
                        </pre>
                    </template>
                </el-table-column> 
           
                <el-table-column  type='index' > </el-table-column>         
                <el-table-column  label="角色名称" prop='roleName' ></el-table-column>          
                <el-table-column  label="角色描述" prop='roleDesc' ></el-table-column>
                <el-table-column  label="操作" width='320px'>
                    <template slot-scope="scope">
                        <el-button size='mini' type="primary" icon="el-icon-edit" @click='editRightDialog(scope.row.id)'>编辑</el-button>
                        <el-button size='mini' type="danger" icon="el-icon-share" @click='deleteRightDialog(scope.row.id)'>删除</el-button>
                        <el-button size='mini' type="warning" icon="el-icon-setting" @click='setRightDialog(scope.row)'>分配权限</el-button>
                    </template>
                </el-table-column>       
            </el-table>
    </el-card>


    <!-- 分配权限的对话框 -->
    <el-dialog  :data='rightsList' title="分配权限"  :visible.sync="setRightDialogVisible"
    width="50%" @close='setRightDialogClosed'>
        <el-tree :data="rightsList" :props="treeProps" show-checkbox  node-key="id" default-expand-all 
        :default-checked-keys='defKeys' ref='treeRef'></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
    </el-dialog>


    <!-- 修改角色列表信息对话框 -->
        <el-dialog title="修改角色信息" :visible.sync="editRightDialogVisible" width="50%"  >
        <el-form :model="RoleInfo">
            <el-form-item label="角色ID" >
                <el-input v-model="RoleInfo.roleId" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop='roleName'>
                <el-input v-model="RoleInfo.roleName" ></el-input>

            </el-form-item>
            <el-form-item label="角色描述" prop='roleDesc'>
                <el-input v-model="RoleInfo.roleDesc" ></el-input>
            </el-form-item>
        </el-form>
        
        <span slot="footer" class="dialog-footer">
            <el-button @click="editRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        </span>
        </el-dialog>


</div>
    
</template>
<script>
export default {
    data(){
        return{
            // 角色列表
            rolesList:[],
            // 控制分配权限对话框
            setRightDialogVisible:false,

            // 控制修改角色列表信息对话框
            editRightDialogVisible:false,

            // 权限列表
            rightsList:[],
             // 展示权限列表的树形控件
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            // 勾选默认的节点id数组
            defKeys:[],
            // 当前即将分配权限的角色id
            roleId:'',
            // 根据 ID 查询角色
            RoleInfo:{},


        }

    },
    created(){
        this.getRolesList()
    },
    methods:{
        async getRolesList(){
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status!==200){
                return this.$message.error('获取角色列表失败！')

            }
            // 挂载获取的数据
            this.rolesList=res.data


        },
    //    根据id删除对应权限
        async removeRightById(role,rightId){
        //    this.$http.delete('roles/:roleId/rights/:rightId')
        //    提示用户是否确定删除
            const confirmResult =await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err=>{
            return err
        })
        // console.log(confirmResult)
        if(confirmResult!=='confirm'){
            this.$message.info('已取消删除')

        }
        // console.log(role)
       /*  :roleId  | 角色 ID  
        :rightId | 权限 ID   */
        
        const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        // console.log(res)

        //  console.log(res)
        if(res.meta.status!==200){
           return this.$message.error('删除权限失败')

        }
        // 会重新渲染整个页面
        // this.getRolesList()
        role.children=res.data
   
    },
       


    //    展示分配权限的对话框
    async setRightDialog(role){
            // 角色授权提供角色id
            this.roleId=role.id
            const {data:res}= await this.$http.get('rights/tree')
            
            if(res.meta.status!==200){
               return this.$message.error('获取权限列表失败！')

            }          
            // 挂载获取的数据
            this.rightsList=res.data
            // 递归获取三级节点的Id
            this.getLeafKeys(role,this.defKeys)
            this.setRightDialogVisible=true

        },
    // 递归获取角色下所有的三级权限的id，并保存至defKeys数组中
    getLeafKeys(node,arr){
        //如果当前节点为三级节点，则没有children属性
        if(!node.children){
            return arr.push(node.id)
            
        }
        node.children.forEach(item =>{this.getLeafKeys(item,arr)})

    },

    // 监听分配权限对话框关闭事件

    // 解决再次点击其他角色的时候，上一个角色的id已经保存在数组中
    setRightDialogClosed(){
        this.defKeys=[]
    },
    // 点击为角色分配权限
    async allotRights(){
        const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
       const idStr = keys.join(',')
       const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
       if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }

      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    
    // 编辑角色列表信息
    async editRightDialog(roleId){
        // console.log(roleId)

        
        const {data:res} =await this.$http.get('roles/'+roleId)
        console.log(res.data)
        if(res.meta.status!==200){
            return this.$message.error('获取角色信息失败')

        }
        this.$message.success(res.meta.msg)
        this.RoleInfo=res.data
        this.editRightDialogVisible=true

    },
    
    // 点击按钮，修改角色信息
    async editRoleInfo(){
        // console.log(this.RoleInfo.roleId)
        const {data:res} = await this.$http.put('roles/'+this.RoleInfo.roleId,{
            roleName:this.RoleInfo.roleName,
            roleDesc:this.RoleInfo.roleDesc
        })
        console.log(res.data)
        // console.log(this.$http.put('roles/'+this.RoleInfo.roleId))
        if(res.meta.status!==200){
            return this.$message.error('修改失败')
        } 
        this.$message.success('编辑提交成功')
        this.editRightDialogVisible =false
        this.getRolesList()


    },
    
    // 根据id删除角色
    async deleteRightDialog(id){
        // console.log(id)

        //   <!-- 提示用户是否确定删除 -->
        const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        console.log(confirmResult)
        if(confirmResult!=='confirm'){
            return this.$message.info('已取消删除')

        }
        const {data:res} =await this.$http.delete('roles/'+id)
        if(res.meta.status !== 200){
             return this.$message.error('删除角色失败！')

        }
            this.$message.success('删除角色成功！')
            this.getRolesList()
        


    }


    }
    
}
</script>
<style lang="less" scoped>

</style>